//
//  WDEditLoanController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2017/1/3.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "WDEditLoanController.h"
#import "WDCarTypeController.h"
#import "WDFinancialProductController.h"
#import "WDBusinessListController.h"
#import "WDEditHeadView.h"
#import "WDLoan.h"
#import "WDLoanEditCell.h"
#import "WDDataInformation.h"
#import "WDData.h"
#import "WDMaterialDetail.h"
#import "WDUploadData.h"
#import "WDOriImageController.h"
#import "WDLoanSubmitController.h"

@interface WDEditLoanController () <UITableViewDelegate, UITableViewDataSource, WDEditHeadViewDelegate, WDLoanEditCellDelegate>
/** tableView */
@property (nonatomic, strong) UITableView *tableView;
/** 拍摄资料标题 */
@property (nonatomic, strong) NSArray *dataArray;
/** 图片信息 */
@property (nonatomic, strong) NSMutableArray *images;
/** 是不是第一次进 */
@property(nonatomic, assign) BOOL isFirstCome;
/** 头部视图 */
@property (nonatomic, strong) WDEditHeadView *headView;
/** 删除的ID集合 存进字符串中，用","隔开 */
@property (nonatomic, strong) NSMutableArray *deleStrArr;
/** 是否进入编辑模式 */
@property (nonatomic, assign) BOOL isEditMode;

@end

@implementation WDEditLoanController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.deleStrArr = [NSMutableArray array];
    
    [self loadNavItemWithLeftAction:@selector(backBtn) leftBtnImage:@"icon_back" leftBtnSelImage:@"icon_back" title:@"编辑订单" rihgtAction:@selector(sureBtn) rightStr:@"确认"];
    
    self.isFirstCome = YES;
    
    //编辑模式默认是NO
    self.isEditMode = NO;
    
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"isEditMode" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveSelectNoti:) name:@"isChoosed" object:nil];
    
    [self loadTableView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    
    if (self.isFirstCome) {
        //进入页面时遍历数据库，把状态为error和running的变为为writing
        WDSQLiteManager *manager = [WDSQLiteManager manager];
        
        //查询完成的数据
        NSArray *deleData = [manager selectWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"status":@(UploadStatusFinish)}];
        
        //把网络上的图片和完成的从数据库中删除
        [manager deleteWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"status":@(UploadStatusFinish)}];
        
        WDUploadData *tempData = [[WDUploadData alloc] init];
        for (tempData in deleData) {
            //把图片从本地删除
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //判断存不存在
            BOOL isExist = [fileManager fileExistsAtPath:[WDCachePath stringByAppendingPathComponent:tempData.imagePath]];
            if (isExist) {
                //WDLog(@"图片存在");
            } else {
                //WDLog(@"图片不存在");
            }
            
            //返回是否删除
            if (tempData.imagePath) {
                
                BOOL isDele = [fileManager removeItemAtPath:[WDCachePath stringByAppendingPathComponent:tempData.imagePath] error:nil];
                if (isDele) {
                    //WDLog(@"删除成功");
                } else {
                    //WDLog(@"删除失败");
                }
            }
            
        }
        
        //重新请求数据
        [self requestMaterialDetail];
    }
    self.isFirstCome = NO;
    
}

- (void)loadTableView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, WDScreenH - 64) style:UITableViewStyleGrouped];
    tableView.backgroundColor = WDBackColor;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    WDEditHeadView *headView = [WDEditHeadView editHeadView];
    headView.loan = self.loan;
    CGRect newFrame = CGRectMake(0, 0, WDScreenW, self.loan.detailHeadH);
    
    headView.delegate = self;
    
    headView.frame = newFrame;
    
    self.headView = headView;
    
    [self.tableView setTableHeaderView:headView];
}

- (void)backBtn
{
    [self showAlertWithTitle:@"提醒" Message:@"您是否要放弃编辑请款？" leftStr:@"是" rightStr:@"否" leftBtnClick:^{
        [self.navigationController popViewControllerAnimated:YES];
    } rightClick:^{
        
    }];
}

- (void)sureBtn
{
    [self.view endEditing:YES];
    
    //验证数据
    WDSQLiteManager *manager = [WDSQLiteManager manager];
    
    self.images = (NSMutableArray *)[manager selectWithTable:NSStringFromClass([WDUploadData class])];
    
    NSArray *waittingArr = [manager selectWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"status":@(UploadStatusWaiting)}];
    
    if ([self.loan.user_name isEqualToString:@""]) {
        [WDPromptBox showPromptBoxWithMassage:@"请输入正确的姓名"];
    } else if (self.loan.phone.length != 11){
        [WDPromptBox showPromptBoxWithMassage:@"请输入正确手机号"];
    } else if ([self.loan.car_price isEqualToString:@""]) {
        [WDPromptBox showPromptBoxWithMassage:@"请输入正确的车辆价格"];
    } else if ([self.loan.loan_amount isEqualToString:@""]) {
        [WDPromptBox showPromptBoxWithMassage:@"请输入正确的贷款金额"];
    } else if (!self.images.count){
        [self showAlertWithMessage:@"资料不能为空，请上传相关资料"];
    } else if (waittingArr.count) {
        [WDPromptBox showPromptBoxWithMassage:@"资料正在上传，请上传完再提交"];
    } else {
        [self showAlertWithTitle:@"提示" Message:@"请核对信息和图片，提交后将不能更改，您确定要提交吗" leftStr:@"确定" rightStr:@"取消" leftBtnClick:^{
            
            [self updateLoanMessage];
            
            //跳转提交成功页面
            WDLoanSubmitController *tempVC = [[WDLoanSubmitController alloc] init];
            tempVC.view.backgroundColor = WDBackColor;
            
            [self.navigationController pushViewController:tempVC animated:YES];
            
        } rightClick:^{
            
        }];
    }
}

- (void)cancelBtn
{
    self.isEditMode = NO;
    
    [self.deleStrArr removeAllObjects];
    
    [self loadNavItemWithLeftAction:@selector(backBtn) leftBtnImage:@"icon_back" leftBtnSelImage:@"icon_back" title:@"编辑订单" rihgtAction:@selector(sureBtn) rightStr:@"确认"];
    
    //
    [self.tableView reloadData];
}

- (void)deleteBtn
{
    if ([self.deleStrArr count]) {
        
        [self requestDelete];
    } else {
        
        [WDPromptBox showPromptBoxWithMassage:@"没有可删除的图片"];
    }
    
}

#pragma mark - 请求数据
/** 请求材料数据 */
- (void)requestMaterialDetail
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"finance_id":self.loan.id,
                                 @"material_type":@1,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceFileList];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //WDLog(@"%@",responseObject);
        WDDataInformation *dataInformation = [WDDataInformation mj_objectWithKeyValues:responseObject];
        
        self.dataArray = [WDMaterialDetail mj_objectArrayWithKeyValuesArray:dataInformation.material_list];
        
        NSArray *imageData = [WDData mj_objectArrayWithKeyValuesArray:dataInformation.data];
        
        WDSQLiteManager *manager = [WDSQLiteManager manager];
        [manager creatTable:NSStringFromClass([WDUploadData class]) WithPrimaryKey:nil];
        
        if (imageData.count) {
            WDSQLiteManager *manager = [WDSQLiteManager manager];
            [manager creatTable:NSStringFromClass([WDUploadData class]) WithPrimaryKey:nil];
            
            WDData *image = nil;
            WDUploadData *uploadData = [[WDUploadData alloc] init];
            for (image in imageData) {
                uploadData.objectId = image.file_id;
                uploadData.financeId = self.loan.id;
                uploadData.status = UploadStatusFinish;
                uploadData.imageType = [image.file_type integerValue];
                uploadData.imageName = image.file_name;
                uploadData.url = image.url;
                uploadData.thumbUrl = image.thumbnail;
                uploadData.mimeType = @"image/jpeg";
                
                //插入数据
                [manager insertWithTable:NSStringFromClass([WDUploadData class]) andModel:uploadData];
            }
            
            //遍历数据库
            self.images = (NSMutableArray *)[manager selectWithTable:NSStringFromClass([WDUploadData class])];
        } else {
            //遍历数据库
            self.images = (NSMutableArray *)[manager selectWithTable:NSStringFromClass([WDUploadData class])];
        }
        
        if(self.dataArray.count == 0) {
            WDMaterialDetail *material0 = [self creatMaterialWithId:@"100" name:@"身份证"];
            WDMaterialDetail *material1 = [self creatMaterialWithId:@"101" name:@"驾驶证"];
            WDMaterialDetail *material2 = [self creatMaterialWithId:@"103" name:@"还款银行卡"];
            WDMaterialDetail *material3 = [self creatMaterialWithId:@"105" name:@"银行流水"];
            WDMaterialDetail *material4 = [self creatMaterialWithId:@"106" name:@"居住证明"];
            WDMaterialDetail *material5 = [self creatMaterialWithId:@"111" name:@"工作证明"];
            WDMaterialDetail *material6 = [self creatMaterialWithId:@"112" name:@"征信授权"];
            WDMaterialDetail *material7 = [self creatMaterialWithId:@"120" name:@"申请表"];
            WDMaterialDetail *material8 = [self creatMaterialWithId:@"200" name:@"其他"];
            self.dataArray = @[material0,material1,material2,material3,material4,material5,material6,material7,material8];
        }
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //WDLog(@"%@", error);
        
    }];
}

- (WDMaterialDetail *)creatMaterialWithId:(NSString *)id name:(NSString *)name
{
    WDMaterialDetail *material = [[WDMaterialDetail alloc] init];
    material.id = id;
    material.name = name;
    
    return material;
}

/** 更新贷款信息 */
- (void)updateLoanMessage
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    NSDictionary *parameters;
    if (![self.loan.remark isEqualToString:@""] && self.loan.remark) {
        parameters = @{
                       @"id":self.loan.id,
                       @"is_throw":@0,
                       @"city_id":self.loan.city_id,
                       @"user_name":self.loan.user_name,
                       @"phone":self.loan.phone,
                       @"car_type":self.loan.car_type,
                       @"brand_id":self.loan.brand_id,
                       @"brand_name":self.loan.brand_name,
                       @"series_id":self.loan.series_id,
                       @"series_name":self.loan.series_name,
                       @"car_price":self.loan.car_price,
                       @"product_id":self.loan.product_id,
                       @"product_name":self.loan.product_name,
                       @"loan_amount":self.loan.loan_amount,
                       @"pay_periods":self.loan.pay_periods,
                       @"supplier_id":self.loan.supplier_id,
                       @"supplier_name":self.loan.supplier_name,
                       @"remark":self.loan.remark,
                       @"material_type":@1,
                       @"ctype":@3
                       };
    } else {
        
        parameters = @{
                       @"id":self.loan.id,
                       @"is_throw":@0,
                       @"city_id":self.loan.city_id,
                       @"user_name":self.loan.user_name,
                       @"phone":self.loan.phone,
                       @"car_type":self.loan.car_type,
                       @"brand_id":self.loan.brand_id,
                       @"brand_name":self.loan.brand_name,
                       @"series_id":self.loan.series_id,
                       @"series_name":self.loan.series_name,
                       @"car_price":self.loan.car_price,
                       @"product_id":self.loan.product_id,
                       @"product_name":self.loan.product_name,
                       @"loan_amount":self.loan.loan_amount,
                       @"pay_periods":self.loan.pay_periods,
                       @"supplier_id":self.loan.supplier_id,
                       @"supplier_name":self.loan.supplier_name,
                       @"material_type":@1,
                       @"ctype":@3
                       };
    }
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceUpdate];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self finaiceCommit];
        
        //WDLog(@"%@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //WDLog(@"%@", error);
        
    }];
}

- (void)finaiceCommit
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"finance_id":self.loan.id,
                                 @"cype":@3
                                 };
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceCommit];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //WDLog(@"%@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //WDLog(@"%@", error);
        
    }];
}

/** 删除图片接口 */
- (void)requestDelete
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    //NSArray数组转json数组
    NSString *deleStr = [self.deleStrArr mj_JSONString];
    
    NSDictionary *parameters = @{
                                 @"file_ids":deleStr,
                                 @"material_type":@1,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceFileDel];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"error_msg"] isEqualToString:@"success"]) {//删除成功
            //从数据库中删除
            for (NSString *objectId in self.deleStrArr) {
                [[WDSQLiteManager manager] deleteWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"objectId":objectId}];
            }
            
            //查询更新
            self.images = (NSMutableArray *)[[WDSQLiteManager manager] selectWithTable:NSStringFromClass([WDUploadData class])];
            
            self.isEditMode = NO;
            
            [self cancelBtn];
        } else {
            
            [WDPromptBox showPromptBoxWithMassage:responseObject[@"error_msg"]];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        WDLog(@"%@", error);
        
    }];
}

#pragma mark - 收到通知
/** 长按进入编辑模式 */
- (void)receiveNotification:(NSNotification *)noti
{
    self.isEditMode = YES;
    
    [self loadNavItemWithLeftAction:@selector(cancelBtn) leftBtnStr:@"取消" title:@"编辑订单" rihgtAction:@selector(deleteBtn) rightStr:@"删除"];
    
    [self.tableView reloadData];
    
    WDLog(@"收到通知 -%@- -%@- -%@-", noti.object, noti.userInfo, noti.name);
}

/** 选择图片是否删除 */
- (void)receiveSelectNoti:(NSNotification *)noti
{
    if ([noti.userInfo[@"selectStatus"] integerValue] == 1) {
        
        [self.deleStrArr addObject:noti.userInfo[@"seleStr"]];
        
        WDLog(@"%@", self.deleStrArr);
        
    } else {
        
        [self.deleStrArr removeObject:noti.userInfo[@"seleStr"]];
        
        WDLog(@"%@", self.deleStrArr);
    }
    
    WDLog(@"收到通知 -%@- -%@- -%@-", noti.object, noti.userInfo, noti.name);
}

#pragma mark - tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDLoanEditCell *cell = [WDLoanEditCell loanEditCellWithTableView:tableView indexPath:indexPath];
    cell.delegate = self;
    cell.isEditMode = self.isEditMode;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row == 0 && indexPath.row != (self.dataArray.count - 1)) {
        cell.firstCell = YES;
    } else if (indexPath.row == (self.dataArray.count - 1)) {
        cell.firstCell = NO;
        cell.lastCell = YES;
    } else {
        cell.firstCell = NO;
        cell.lastCell = NO;
    }
    cell.financeID = self.loan.id;
    cell.materialDetail = self.dataArray[indexPath.row];
    cell.index = indexPath.row;
    
    NSArray *imageArr = [[WDSQLiteManager manager] selectWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"imageType":@([cell.materialDetail.id integerValue])}];
    cell.materialDetail.DetailCellH = ((imageArr.count / 2) + 1) * 102;
    cell.imagesData = (NSMutableArray *)imageArr;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDMaterialDetail *materialDetail =self.dataArray[indexPath.row];
    
    if (indexPath.row == self.dataArray.count - 1) {
        return materialDetail.DetailCellH + 60;
    } else {
        return materialDetail.DetailCellH + 20;
    }
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1.0;
}

#pragma mark - <WDEditHeadViewDelegate>
- (void)jumpPage:(WDJumpType)jumpType viewController:(UIViewController *)viewController
{
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)updataHeadViewH:(CGFloat)heightH
{
    CGRect newFrame = self.headView.frame;
    
    newFrame.size.height = heightH;
    
    self.headView.frame = newFrame;
    
    [self.tableView reloadData];
}

#pragma mark - <WDEditCellDelegate>
//跳转原图
- (void)loanEditShowOriginalImage:(NSArray *)images clickIndex:(NSInteger)index
{
    WDOriImageController *tempV = [[WDOriImageController alloc] init];
    tempV.images = images;
    tempV.index = index;
    tempV.view.backgroundColor = WDBackColor;
    
    [self.navigationController pushViewController:tempV animated:YES];
}

- (void)reloadDataTableView:(NSInteger)index collectionView:(NSInteger)itemNum
{
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:index inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)loanEditShowAlert:(UIAlertController *)alert
{
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)loanEditOpenImagePicker:(UIImagePickerController *)picker
{
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)dealloc
{
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
